/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ericsson.nfc.signing.record;

/**
 *
 * @author emarkki
 */
public class SignatureField {
    
    public static final int RSASSA_PSS = 0x01;
    public static final int RSASSA_PKCS1_V1_5_WITH_SHA1 = 0x02;
    public static final int DSA = 0x03;
    public static final int ECDSA_P_192_SHA1 = 0x04;
    
    private int type;
    private byte[] bytes;
    private URIRecord uri;

    public SignatureField(int signatureType, byte[] signature) {
        this(signatureType, signature, null);
    }

    public SignatureField(int signatureType, URIRecord signatureUri) {
        this(signatureType, null, signatureUri);
    }

    private SignatureField() {
    }
    
    private SignatureField(int signatureType, byte[] signature, URIRecord signatureUri) {
        this.type = signatureType;
        this.bytes = signature;
        this.uri = signatureUri;
        
        if(signature == null && signatureUri == null) {
            throw new IllegalArgumentException("No signature specified");
        }
        
        if(signatureType >= 0x05) {
            throw new IllegalArgumentException("Invalid signature record due to use of RFU signature type"); // TODO: Perhaps move this check to higher level logic
        }
    }

    static SignatureField createMark() {
        return new SignatureField();
    }

    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final SignatureField other = (SignatureField) obj;
        if (this.type != other.type) {
            return false;
        }
        if (this.bytes != other.bytes && (this.bytes == null || !Arrays.equals(this.bytes, other.bytes))) {
            return false;
        }
        if (this.uri != other.uri && (this.uri == null || !this.uri.equals(other.uri))) {
            return false;
        }
        return true;
    }

    public int hashCode() {
        int hash = 7;
        hash = 11 * hash + this.type;
        hash = 11 * hash + (this.bytes != null ? Arrays.hashCode(this.bytes) : 0);
        hash = 11 * hash + (this.uri != null ? this.uri.hashCode() : 0);
        return hash;
    }

    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("Sig(");
        if(getSignature() != null) {
            sb.append("len:");
            sb.append(getSignature().length);
            sb.append(", ");
        }
        if(getUri() != null) {
            sb.append("uri:");
            sb.append(getUri());
        }
        sb.append(")");
        return sb.toString();
    }
    
    public byte[] getSignature() {
        return bytes;
    }

    public int getType() {
        return type;
    }

    public URIRecord getUri() {
        return uri;
    }
    
}
